package com.zxn.xiaoran.model.api;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.util.Auth;
import com.zxn.presenter.model.IApiFactory;
import com.zxn.xiaoran.model.http.BasicParamsInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by zxn on 2019/5/8.
 */
public class ApiFactory implements IApiFactory {
    protected int mMode = MODE_ON_LINE;
    protected String mDevelopModeUrl = URL_ON_LINE;

    // 线上
    public static final String URL_ON_LINE = "http://api.liantuofu.com/";
    //测试
    public static final String URL_ON_TEST = "http://testclubshop.liantuobank.com/";
    //灰度.
    public static final String URL_ON_GRAY = "http://intshop.51ebill.com/";
    //七牛
    //http://pve2vnnyq.bkt.clouddn.com/IMG_20190517_151606.jpg
    public static final String URL_ON_QINIU = "http://pve2vnnyq.bkt.clouddn.com/";


    // 版本信息线上
    protected static final String URL_ON_LINE_51EBILL = "http://front.51ebill.com/";
    protected static String PARTNER_ID_ON_LINE_51EBILL = "10023887795150716";
    protected static final String PARTNER_KEY_ON_LINE_51EBILL = "C98C59D62253844A26094DDF53CA4013";


    //版本信息测试
    protected static final String URL_ON_TEST_51EBILL = "http://testfront.51ebill.com:65527/";
    protected static String PARTNER_ID_ON_TEST_51EBILL = "10012374813150618";
    protected static final String PARTNER_KEY_ON_TEST_51EBILL = "4E5C96CEF8FD2CA317E6B748D9F9213B";

    protected String m51EbillUrl = URL_ON_LINE_51EBILL;

    protected final OkHttpClient.Builder mBuilder;
    protected OkHttpClient mOkHttpClient;
    protected Retrofit.Builder mRetrofitBuilder;
    protected Retrofit mRetrofit;
    protected Gson mGson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
            .serializeNulls()
            .create();
    private final IXMApi mXMApi;
    private final IBaiduTTL mIBaiduTTL;
    private final IQiniuApi mIQiniuApi;

    protected ApiFactory() {
        mBuilder = new OkHttpClient
                .Builder()
                .connectTimeout(1000L * 15, TimeUnit.MILLISECONDS)
                .readTimeout(1000L * 10, TimeUnit.MILLISECONDS)
                .writeTimeout(1000L * 10, TimeUnit.MILLISECONDS);
        Cache cache = getCache();
        if (cache != null) {
            mBuilder.cache(cache);
        }

//        if (isShowLog()) {
//        }

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        mBuilder.addInterceptor(loggingInterceptor);

        mOkHttpClient = mBuilder.build();
        mRetrofitBuilder = new Retrofit.Builder();

        mRetrofitBuilder = mRetrofitBuilder
//                .baseUrl(mDevelopModeUrl)
                .client(mOkHttpClient)
                .addConverterFactory(GsonConverterFactory.create(mGson))//
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//设置支持返回Rxjava类型，支持返回类型为rx.Observable、rx.Single、rx.Completable
                .addConverterFactory(ScalarsConverterFactory.create());


//        mMerchantApi = mRetrofit.create(IXMApi.class);

        mXMApi = mRetrofitBuilder
                .baseUrl("https://www.pgyer.com")
                .build().create(IXMApi.class);

        mIBaiduTTL = mRetrofitBuilder
                .baseUrl("https://aip.baidubce.com/")
                .build().create(IBaiduTTL.class);


        mIQiniuApi = mRetrofitBuilder
                .client(mBuilder.addInterceptor(new BasicParamsInterceptor()).build())
                .baseUrl("http://rsf.qbox.me/")
                .build().create(IQiniuApi.class);

        mUploadManager = new UploadManager();
    }

    protected boolean isShowLog() {
//        return BaseApp.isDebug();
        return true;
    }

    private static class SingleInstance {
        private static final ApiFactory INSTANVE = new ApiFactory();
    }

    public static ApiFactory getInstance() {
        return SingleInstance.INSTANVE;
    }

    protected Cache getCache() {
        return null;
    }


    @Override
    public void setMode(int mode) {
        this.mMode = mode;
        if (mMode == MODE_ON_LINE) {
            mDevelopModeUrl = URL_ON_LINE;
            m51EbillUrl = URL_ON_LINE_51EBILL;
        } else if (mMode == MODE_ON_TEST) {
            mDevelopModeUrl = URL_ON_TEST;
            m51EbillUrl = URL_ON_TEST_51EBILL;
        } else if (mMode == MODE_ON_GRAY) {
            mDevelopModeUrl = URL_ON_GRAY;
            m51EbillUrl = URL_ON_TEST_51EBILL;
        }
        mRetrofitBuilder
                .baseUrl(mDevelopModeUrl)
                .build();
    }

    public OkHttpClient getOkHttpClient() {
        return mOkHttpClient;
    }

    public IXMApi getXMApi() {
        return mXMApi;
    }

    public IBaiduTTL getIBaiduTTL() {
        return mIBaiduTTL;
    }

    public IQiniuApi getIQiniuApi() {
        return mIQiniuApi;
    }

    private UploadManager mUploadManager;
    private static final String ACCESS_KEY = "d7ey2oI9vmgg_kpp_yBEA-QjzH3hxtkKsiafwnRt";
    private static final String SECRET_KEY = "Pn98j0k60XsT9HMq_NiC1s8UiWAR3h1sM-VZYZgJ";
    public static final String BUCKET_NAME = "zxn0721";

    public void put(String filePath, String key, UpCompletionHandler completionHandler) {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String token = auth.uploadToken(BUCKET_NAME);
        mUploadManager.put(filePath, key, token, completionHandler, null);
    }

    /**
     * 上传图片并且带有上传进度.
     *
     * @param filePath
     * @param key
     * @param completionHandler
     */
    public void putWithProgress(String filePath, String key, UpCompletionHandler completionHandler) {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String token = auth.uploadToken(BUCKET_NAME);
        mUploadManager.put(filePath, key, token, completionHandler,
                new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            public void progress(String key, double percent) {
                                Log.i("qiniu", key + ": " + percent);
                            }
                        }, null));
    }

    public String uploadToken() {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        return auth.uploadToken(BUCKET_NAME);
    }

    public String sign(String data) {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        return auth.sign(data);
    }

    public String signWithData(String data) {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        return auth.signWithData(data);
    }

    public String signRequest(String urlString) {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        return "QBox " + auth.signRequest(urlString, null, "application/json");
    }

    public boolean isValidCallback(String originAuthorization,String url) {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        return auth.isValidCallback(originAuthorization,url,null,"application/json");
    }

}
